import { DeleteOutlined, PlusOutlined } from "@ant-design/icons"
import { ProCard, BetaSchemaForm, ProTable, ProColumns, ActionType } from "@ant-design/pro-components"
import { Button, Form, Menu, Popconfirm, message } from "antd"
import React, { useRef } from "react"
import { addRoleByAccountId, deleteRoleByAccountId } from "../service"
import { getRolePage } from "../../role/service"

const Permission: React.FC<any> = ({
  currentRole,
  accountPermissionData,
  setCurrentRole,
  actionRef,
  currentRow,
  refresh,
}) => {
  const [addPermissionForm] = Form.useForm()

  const permissionColumns: ProColumns<any>[] = [
    {
      title: '权限名称',
      dataIndex: 'name',
      formItemProps: {
        rules: [{ required: true }]
      }
    },
    {
      title: '权限编码',
      dataIndex: 'code',
      // valueType: 'code',
      formItemProps: {
        rules: [{ required: true }]
      },
      render(dom, entity, index, action, schema) {
        return <div style={{ backgroundColor: 'rgba(150, 150, 150, 0.1)', padding: '5px 10px', display: 'inline-block' }}>{dom}</div>
      },
    },
    {
      title: '权限描述',
      dataIndex: 'description',
      valueType: 'textarea',
    },
  ]

  return <>
    <ProCard split="vertical">
      <ProCard colSpan="284px" title="角色" extra={<BetaSchemaForm<any>
        key={'add'}
        layoutType="ModalForm"
        form={addPermissionForm}
        modalProps={{
          title: '关联角色',
          width: 500,
        }}
        columns={[
          {
            title: '选择角色',
            dataIndex: 'roleId',
            valueType: 'select',
            formItemProps: {
              rules: [{ required: true, message: '请选择角色!' }]
            },
            async request() {
              const res = await getRolePage({
                current: 1,
                pageSize: 200,
              })

              return res?.data?.currentData?.map((item: any) => ({
                ...item,
                label: item.name,
                value: item.id
              })) || []
            }
          }
        ]}
        trigger={<Button onClick={() => {
          addPermissionForm.resetFields()
        }}
          icon={<PlusOutlined />}>新增</Button>}
        onFinish={async (values) => {
          const hide = message.loading('正在添加');

          try {
            const res = await addRoleByAccountId({ ...values, accountId: currentRow?.id });
            hide();
            if (res.code == 0) {
              message.success('添加成功');
              refresh()
              return true;
            }
          } catch (error) {
            hide();
            message.error('添加失败请重试！');
            return false;
          }
        }} />}>
        <Menu
          selectedKeys={currentRole ? [currentRole] : undefined}
          style={{ border: 'none' }}
          items={accountPermissionData?.roleList?.map((item: any) => ({
            label: <div style={{
              alignItems: 'center',
              justifyContent: 'space-between', display: 'flex'
            }}>
              <div>{item.name}</div>
              <Popconfirm key='del' title="是否要与此角色取消关联？" onConfirm={async () => {
                const hide = message.loading('正在移除角色');

                try {
                  const res = await deleteRoleByAccountId({ roleId: item?.id, accountId: currentRow?.id });
                  hide();
                  if (res.code == 0) {
                    message.success('移除角色成功');
                    refresh()
                    return true;
                  }
                } catch (error) {
                  hide();
                  message.error('移除角色失败请重试！');
                  return false;
                }
              }}>
                <Button size='small' icon={<DeleteOutlined />}></Button>
              </Popconfirm>
            </div>,
            value: item.id,
            key: item.id,
          }))}
          onSelect={node => {
            setCurrentRole(node.key)
          }}
        />
      </ProCard>
      <ProCard
        title={'权限列表'}
       >
        <ProTable<any>
          columns={permissionColumns}
          toolBarRender={false}
          dataSource={accountPermissionData?.roleList?.find((item: any) => item.id == currentRole)?.permissionList}
          rowKey="id"
          search={false}
          options={false}
          dateFormatter="string"
        />
      </ProCard>
    </ProCard >
  </>
}

export default Permission